using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Media;
using NewtonDynamics;

namespace WPFPhysics1
{
	public class StrokeAdapter : Bodies
	{
		private StrokeCollection strokes;

		public StrokeAdapter( double worldWidth, double worldHeight ) : base( worldWidth, worldHeight )
		{
			
		}

		public void Initialize( StrokeCollection strokes, double displayWidth, double displayHeight )
		{
			foreach ( CBody body in this )
			{
				if ( body != null ) body.Dispose();
			}

			Clear();

			double height = displayHeight;
			double width = height * ( worldWidth / worldHeight );

			this.strokes = strokes;

			double xScale = worldWidth / width;
			double yScale = worldHeight / height;

			AddRectangle( 0, 3, 10, 0.2, 10, true );

			foreach ( Stroke stroke in strokes )
			{
				List<Vector> vertices = new List<Vector>();

				PathGeometry geometry = stroke.GetGeometry().GetFlattenedPathGeometry( 10, ToleranceType.Absolute );
				Rect rect = geometry.Bounds;

				foreach ( PathFigure figure in geometry.Figures )
				{
					foreach ( PathSegment segment in figure.Segments )
					{
						LineSegment line = segment as LineSegment;

						if ( line != null )
						{
							vertices.Add( new Vector(
								( ( line.Point.X - rect.Left - ( rect.Width / 2 ) ) * xScale ),
								( ( line.Point.Y - rect.Top - ( rect.Height / 2 ) ) * yScale ) ) );
						}

						PolyLineSegment polyLine = segment as PolyLineSegment;

						if ( polyLine != null )
						{
							foreach ( Point point in polyLine.Points )
							{
								vertices.Add( new Vector(
									( ( point.X - rect.Left - ( rect.Width / 2 ) ) * xScale ),
									( ( point.Y - rect.Top - ( rect.Height / 2 ) ) * yScale ) ) );
							}
						}
					}
				}

				AddPolygon(
					( ( rect.X + ( rect.Width / 2 ) ) * xScale ) - ( worldWidth / 2 ),
					( ( rect.Y + ( rect.Height / 2 ) ) * yScale ) - ( worldHeight / 2 ),
					vertices.ToArray() );
			}
		}

		public StrokeCollection Strokes
		{
			get { return strokes; }
			set { strokes = value; }
		}
	}
}